package main

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"sofuny/config"
	"sofuny/controls"
	"sofuny/models"
	"sofuny/router"
	"sofuny/utils"
	"strings"
	"time"
)

func init() {
	models.MigrateDB()
}

// app
var appConfig = config.App()

func main() {

	// 定时任务
	c := cron.New(cron.WithSeconds())
	// 早上七点发送邮件
	_, _ = c.AddFunc("CRON_TZ=Asia/Shanghai 00 00 07 * * *", func() {
		sentence := controls.RandomSentenceForEmail()
		subscribes := controls.AllSubscribes()

		// 判断句子和邮箱是否为空
		if sentence.Content == "" || len(subscribes) == 0{ }
		var List [] string
		var Type string
		for _, item := range subscribes{
			List = append(List, item.Email)
			// 判断类型
			// TODO 这里只会返回最后一个　类型
			switch item.Type {
			case "毒鸡汤":
				Type = item.Type
				break
			case "励志语录":
				Type = item.Type
				break
			default:
				Type = "毒鸡汤"
				break
			}
		}
		// 判断是否发送成功
		if utils.SendMail(
			strings.Join(List, ","),
			appConfig.Name+" | "+Type,
			`<h2>Hi，早上好:</h2>`+
				`<p>  `+sentence.Content+`</p>`+
				`</p style="float:right;color:#999">`+time.Now().Format("2006-01-02 15:04:05")+`</p>`,
		) {
			// 发送成功
			fmt.Println("发送成功-> " + time.Now().Format("2006-01-02 15:04:05"))
		} else {
			// 发送失败
			fmt.Println("发送失败-> " + time.Now().Format("2006-01-02 15:04:05"))
		}
	})

	// 定时删除 快传文件 每隔10秒
	_, _ = c.AddFunc("CRON_TZ=Asia/Shanghai */10 * * * * ?", func() {

		//fmt.Println(utils.FormatTime())
		controls.ClearOutdatedFiles()
	})

	// 定时发送 信件 每隔1秒
	_, _ = c.AddFunc("CRON_TZ=Asia/Shanghai */1 * * * * ?", func() {

		controls.SendLetter()
	})

	// 开启任务
	c.Start()

	// Start router
	router.Start(":8000")

	select {}
}
